package com.codeest.geeknews.util.convert;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class BeanConvertor extends ObjectConvertor {

    public <K, V> V convert(K source, Class<V> target, FieldFilter filter) {
        V targetObj = null;
        try {
            targetObj = target.newInstance();
            Class<?> sourceClassObj = source.getClass();
            String[] sourceFields = filter.fromFields();
            String[] targetFields = filter.toFields();

            for (int i = 0; i < sourceFields.length; i++) {
                String sourceFieldName = sourceFields[i];
                String targetFieldName = targetFields[i];
                String sappend = Character.toUpperCase(sourceFieldName
                        .charAt(0)) + sourceFieldName.substring(1);
                String tappend = Character.toUpperCase(targetFieldName
                        .charAt(0)) + targetFieldName.substring(1);
                String getMethodName = "get" + sappend;
                String setMethodName = "set" + tappend;
                Method getMethod = sourceClassObj
                        .getDeclaredMethod(getMethodName);
                getMethod.setAccessible(true);
                Object attrForOneObj = getMethod.invoke(source);
                Method setMethod = target.getDeclaredMethod(setMethodName,
                        getMethod.getReturnType());
                setMethod.setAccessible(true);
                setMethod.invoke(targetObj, attrForOneObj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetObj;
    }

    public <K, V> ArrayList<V> convert(List<K> sources, Class<V> target, FieldFilter filter) {
        ArrayList<V> convertList = new ArrayList<>();
        for (K item : sources) {
            convertList.add(convert(item, target, filter));
        }
        return convertList;
    }
}